﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using GBFinance.Entity;
using GBFinance.BLL;
using HiLand.Utility.Web;
using GBFinance.Web.Models;
using HiLand.Utility.Finance;
using HiLand.Framework.BusinessCore;
using HiLand.Framework.BusinessCore.BLL;
using HiLand.Utility.Enums;
using HiLand.Utility.Entity;
using HiLand.Utility.Data;
using System.Globalization;
using HiLand.General.Entity;
using HiLand.General.BLL;
using HiLand.General;
using HiLand.Utility4.MVC.Controls;
using HiLand.Utility4.MVC.Data;
using HiLand.Utility4.Data;

namespace GBFinance.Web.Controllers
{
    /// <summary>
    /// 本类不向View公开，为SecuredLoan和UnSecuredLoan的基类，仅仅为子类提供公用方法。
    /// </summary>
    public class BaseLoanController : Controller
    {
        #region step0
        public ActionResult Index()
        {
            LoanCookie loanCookie = LoadCurrentLoanCookie();
            bool isNewBirthLoan = loanCookie.CheckIsNewBirthLoan();
            this.ViewData["isNewBirthLoan"] = isNewBirthLoan;
            return View();
        }

        [HttpPost]
        public ActionResult Index(bool resetLoan = false)
        {
            string result = RequestHelper.GetValue("resetLoan");
            if (result == "resetLoan")
            {
                ResetCurrentLoanCookie();
            }
            return View();
        }
        #endregion

        #region step1
        public ActionResult InitialLoanInformation()
        {
            SetCurrentLoanLayout();
            return View();
        }

        public ActionResult UInitialLoanInformation()
        {
            LoanCookie loanCookie = LoadCurrentLoanCookie();
            LoanBasicEntity entity = null;
            if (loanCookie.LoanGuid == string.Empty)
            {
                entity = new LoanBasicEntity();
            }
            else
            {
                entity = LoanBasicBLL.Get(new Guid(loanCookie.LoanGuid));
            }

            BrokeLoanParam();

            return View(entity);
        }

        [HttpPost]
        public ActionResult UInitialLoanInformation(LoanBasicEntity entity)
        {
            LoanCookie loanCookie = LoadCurrentLoanCookie();
            bool isNeedSaveCookie = false;
            bool isNewLoan = false;


            if (entity.LoanGuid == Guid.Empty)
            {
                Guid loanGuid = Guid.Empty;
                if (loanCookie.LoanGuid == string.Empty)
                {
                    loanGuid = Guid.NewGuid();
                    loanCookie.LoanGuid = loanGuid.ToString();
                    isNeedSaveCookie = true;
                }
                else
                {
                    loanGuid = new Guid(loanCookie.LoanGuid);
                }
                entity.LoanGuid = loanGuid;
                isNewLoan = true;
            }
            else
            {
                LoanBasicEntity entityLoaded = LoanBasicBLL.Get(entity.LoanGuid);
                entity.CheckDate = entityLoaded.CheckDate;
                entity.CheckUserID = entityLoaded.CheckUserID;
                entity.LoanDate = entityLoaded.LoanDate;
                entity.LoanInterest = entityLoaded.LoanInterest;
                entity.LoanStatus = entityLoaded.LoanStatus;
                entity.LoanTermType = entityLoaded.LoanTermType;
                entity.LoanType = entityLoaded.LoanType;
                entity.PropertyNames = entityLoaded.PropertyNames;
                entity.PropertyValues = entityLoaded.PropertyValues;
            }

            if (entity.LoanUserID == Guid.Empty)
            {
                Guid enterpriseGuid = Guid.Empty;
                if (loanCookie.EnterpriseGuid == string.Empty)
                {
                    enterpriseGuid = Guid.NewGuid();
                    loanCookie.EnterpriseGuid = enterpriseGuid.ToString();
                    isNeedSaveCookie = true;
                }
                else
                {
                    enterpriseGuid = new Guid(loanCookie.EnterpriseGuid);
                }

                entity.LoanUserID = enterpriseGuid;
            }

            if (isNeedSaveCookie == true)
            {
                loanCookie.Save();
            }

            bool isSuccessful = false;
            if (isNewLoan == true)
            {
                entity.LoanTermType = PaymentTermType.Monthly;
                entity.LoanDate = DateTime.Now;
                entity.LoanInterest = GetCurrentLoanRate();
                entity.LoanStatus = LoanStatuses.UserUnCompleted;
                entity.LoanType = Miscs.GetCurrentLoanType();//LoanTypes.Secured;
                isSuccessful = LoanBasicBLL.Create(entity);
            }
            else
            {
                isSuccessful = LoanBasicBLL.Update(entity);
            }

            SetCurrentLoanStep(10);
            var DataObject = new LogicStatusInfo { IsSuccessful = isSuccessful };

            return Json(DataObject);
        }
        #endregion

        #region step2
        public ActionResult AboutTheApplicants()
        {
            SetCurrentLoanLayout();
            return View();
        }

        /// <summary>
        /// 企业负责人列表
        /// </summary>
        /// <returns></returns>
        public ActionResult UApplicantList()
        {
            BrokeLoanParam();

            List<IBusinessUser> userList = GetApplicantList();
            return View(userList);
        }

        [HttpPost]
        public ActionResult UApplicantList(Guid? entityGuidToDelete)
        {
            BrokeLoanParam();

            if (entityGuidToDelete.HasValue && entityGuidToDelete.Value != Guid.Empty)
            {
                BusinessUserBLL.DeleteUser(entityGuidToDelete.Value);
            }

            List<IBusinessUser> userList = GetApplicantList();
            return View(userList);
        }

        public ActionResult UApplicantDetail(Guid? applicantGuid)
        {
            IBusinessUser applicantUser = new BusinessUser();
            ResidentalEntity residentalEntity = new ResidentalEntity();
            ResidentalEntity residentalEntityPre = new ResidentalEntity();
            if (applicantGuid.HasValue)
            {
                applicantUser = BusinessUserBLL.Get(applicantGuid.Value);
                string whereClause = string.Format("ResidentalUserGuid='{0}'", applicantGuid.Value);
                List<ResidentalEntity> residentalList = ResidentalBLL.GetList(whereClause);
                if (residentalList != null)
                {
                    if (residentalList.Count > 0)
                    {
                        residentalEntity = residentalList[0];
                    }

                    if (residentalList.Count > 1)
                    {
                        residentalEntityPre = residentalList[1];
                    }
                }
            }

            this.ViewBag.ResidentalEntity = residentalEntity;
            this.ViewBag.ResidentalEntityPre = residentalEntityPre;

            return View(applicantUser);
        }

        [HttpPost]
        public ActionResult UApplicantDetail(BusinessUser applicantUser)
        {
            if (applicantUser.UserBirthDay == DateTimeHelper.Min)
            {
                string birthDayFromRequest = RequestHelper.GetValue("UserBirthDay");

                DateTime userBirthDay = DateTimeHelper.Min;

                //TODO:这个地方处理略有奇怪，目前只能手工解析日期字符串形成日期
                try
                {
                    if (string.IsNullOrWhiteSpace(birthDayFromRequest) == false)
                    {
                        string[] birthDayStrings = birthDayFromRequest.Split('/');
                        if (birthDayStrings.Length == 3)
                        {
                            int userBirthYear = Convert.ToInt32(birthDayStrings[2]);
                            int userBirthMonth = Convert.ToInt32(birthDayStrings[1]);
                            int userBirthDate = Convert.ToInt32(birthDayStrings[0]);
                            userBirthDay = new DateTime(userBirthYear, userBirthMonth, userBirthDate);
                        }
                    }
                }
                catch { }

                //DateTime.TryParseExact(birthDayFromRequest,"dd/MM/yyyy", Misc.CurrentCultureInfo, DateTimeStyles.None, out userBirthDay);
                ////DateTime.TryParse(birthDayFromRequest, Misc.CurrentCultureInfo, DateTimeStyles.None, out userBirthDay);
                applicantUser.UserBirthDay = userBirthDay;
            }

            LogicStatusInfo statusInfo = new LogicStatusInfo();

            LoanCookie loanCookie = LoadCurrentLoanCookie();
            if (applicantUser.UserGuid == Guid.Empty)
            {
                applicantUser.UserGuid = Guid.NewGuid();
                applicantUser.DepartmentCode = "outer";
                applicantUser.DepartmentGuid = new Guid(loanCookie.EnterpriseGuid);
                applicantUser.UserRegisterDate = DateTime.Now;
                applicantUser.UserStatus = CommonStatuses.Normal;
                applicantUser.UserType = UserTypes.CommonUser;
                applicantUser.UserName = Guid.NewGuid().ToString();

                CreateUserRoleStatuses createStatus = CreateUserRoleStatuses.Successful;
                BusinessUserBLL.CreateUser(applicantUser, out createStatus);
                if (createStatus == CreateUserRoleStatuses.Successful)
                {
                    statusInfo.IsSuccessful = true;
                    statusInfo.Message = string.Empty;
                }
                else
                {
                    statusInfo.IsSuccessful = false;
                    statusInfo.Message = createStatus.ToString();
                }
            }
            else
            {
                IBusinessUser originalUser = BusinessUserBLL.Get(applicantUser.UserGuid);
                applicantUser.DepartmentCode = originalUser.DepartmentCode;
                applicantUser.DepartmentGuid = originalUser.DepartmentGuid;
                applicantUser.UserRegisterDate = originalUser.UserRegisterDate;
                applicantUser.UserStatus = originalUser.UserStatus;
                applicantUser.UserType = originalUser.UserType;
                applicantUser.UserName = originalUser.UserName;

                bool isSuccessful = BusinessUserBLL.UpdateUser(applicantUser);
                if (isSuccessful == true)
                {
                    statusInfo.IsSuccessful = true;
                    statusInfo.Message = string.Empty;
                }
                else
                {
                    statusInfo.IsSuccessful = false;
                    statusInfo.Message = "error in updating";
                }
            }

            ResidentalEntity residentalEntity = CollectResidentalInfo();
            ResidentalEntity residentalEntityPre = CollectResidentalInfo("Pre");

            string residentalGuid = RequestHelper.GetValue("ResidentalGuid");
            if (string.IsNullOrWhiteSpace(residentalGuid) == false)
            {
                residentalEntity.ResidentialGuid = new Guid( residentalGuid);
            }

            string residentalGuidPre = RequestHelper.GetValue("ResidentalGuidPre");
            if (string.IsNullOrWhiteSpace(residentalGuidPre) == false)
            {
                residentalEntityPre.ResidentialGuid = new Guid(residentalGuidPre);
            }

            string residentalStatusString = RequestHelper.GetValue("ResidentialStatus");
            residentalEntity.ResidentialStatus = EnumHelper.TryParse<ResidentalTypes>(residentalStatusString, ResidentalTypes.OwnHomeWithMortgage);

            residentalEntity.ResidentalUserGuid = applicantUser.UserGuid;
            residentalEntityPre.ResidentalUserGuid = applicantUser.UserGuid;

            if (string.IsNullOrWhiteSpace(residentalGuid) == true || residentalGuid == Guid.Empty.ToString())
            {
                ResidentalBLL.Create(residentalEntity);
            }
            else
            {
                ResidentalBLL.Update(residentalEntity);
            }


            if (string.IsNullOrWhiteSpace(residentalGuidPre) == true || residentalGuidPre == Guid.Empty.ToString())
            {
                ResidentalBLL.Create(residentalEntityPre);
            }
            else
            {
                ResidentalBLL.Update(residentalEntityPre);
            }

            SetCurrentLoanStep(20);

            return Json(statusInfo);
        }

        #region 辅助方法
        private List<IBusinessUser> GetApplicantList()
        {
            List<IBusinessUser> userList = BusinessUserBLL.GetUsersByDepartment(Miscs.CurrentLoanSimpleInfo.EnterpriseGuid);
            return userList;
        }

        private ResidentalEntity CollectResidentalInfo(string prefix = "")
        {
            ResidentalEntity residentalEntity = new ResidentalEntity();
            residentalEntity.ApartmentNo = RequestHelper.GetValue(prefix + "UnitApartmentNo");
            residentalEntity.PostCode = RequestHelper.GetValue(prefix + "Postcode");

            int residentalMonthes = 0;
            int residentalYears = 0;
            int.TryParse(RequestHelper.GetValue(prefix + "AddressMonths"), out residentalMonthes);
            int.TryParse(RequestHelper.GetValue(prefix + "AddressYears"), out residentalYears);
            residentalEntity.ResidentalMonths = residentalMonthes;
            residentalEntity.ResidentalYears = residentalYears;

            residentalEntity.State = RequestHelper.GetValue(prefix + "State");
            residentalEntity.Street = RequestHelper.GetValue(prefix + "StreetNoAndName");
            residentalEntity.Suburb = RequestHelper.GetValue(prefix + "Suburb");

            return residentalEntity;
        }
        #endregion
        #endregion

        #region step3
        public ActionResult AboutYourBusiness()
        {
            SetCurrentLoanLayout();
            return View();
        }


        public ActionResult UAboutYourBusiness()
        {
            BrokeLoanParam();

            EnterpriseEntity enterpriseEntity = new EnterpriseEntity();
            EnterpriseEntity enterpriseRef1 = new EnterpriseEntity();
            EnterpriseEntity enterpriseRef2 = new EnterpriseEntity();

            LoanCookie loanCookie = LoadCurrentLoanCookie(); //CookieInfo.Load<SecuredLoanCookie>();
            string enterpriseGuidString = loanCookie.EnterpriseGuid;
            Guid enterpriseGuid = Guid.Empty;

            if (string.IsNullOrWhiteSpace(enterpriseGuidString) == false && enterpriseGuidString != Guid.Empty.ToString())
            {
                enterpriseGuid = new Guid(enterpriseGuidString);
                enterpriseEntity = EnterpriseBLL.Get(enterpriseGuid);
                if (enterpriseEntity == null)
                {
                    enterpriseEntity = new EnterpriseEntity();
                }
                string whereClause = string.Format("AssociatedEnterpriseGuid='{0}'", enterpriseGuidString);
                List<EnterpriseEntity> enterpriseRefList = EnterpriseBLL.GetList(whereClause);
                if (enterpriseRefList != null)
                {
                    if (enterpriseRefList.Count > 0)
                    {
                        enterpriseRef1 = enterpriseRefList[0];
                    }

                    if (enterpriseRefList.Count > 1)
                    {
                        enterpriseRef2 = enterpriseRefList[1];
                    }
                }
            }

            this.ViewBag.EnterpriseRef1 = enterpriseRef1;
            this.ViewBag.EnterpriseRef2 = enterpriseRef2;

            return View(enterpriseEntity);
        }

        [HttpPost]
        public ActionResult UAboutYourBusiness(EnterpriseEntity entity)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();

            LoanCookie loanCookie = LoadCurrentLoanCookie(); //CookieInfo.Load<SecuredLoanCookie>();
            string enterpriseGuidString = loanCookie.EnterpriseGuid;
            Guid enterpriseGuid = Guid.Empty;
            if (string.IsNullOrWhiteSpace(enterpriseGuidString) || enterpriseGuidString == Guid.Empty.ToString())
            {
                enterpriseGuid = Guid.NewGuid();
            }
            else
            {
                enterpriseGuid = new Guid(enterpriseGuidString);
            }

            EnterpriseEntity enterpriseRef1 = CollecteEnterpriseRef("Ref1");
            EnterpriseEntity enterpriseRef2 = CollecteEnterpriseRef("Ref2");

            enterpriseRef1.AssociatedEnterpriseGuid = enterpriseGuid;
            enterpriseRef2.AssociatedEnterpriseGuid = enterpriseGuid;


            if (entity.EnterpriseID == 0)
            {
                entity.EnterpriseGuid = enterpriseGuid;
                logicStatusInfo.IsSuccessful = EnterpriseBLL.Create(entity);
            }
            else
            {
                logicStatusInfo.IsSuccessful = EnterpriseBLL.Update(entity);
            }

            if (enterpriseRef1.EnterpriseGuid == Guid.Empty)
            {
                enterpriseRef1.EnterpriseGuid = Guid.NewGuid();
                EnterpriseBLL.Create(enterpriseRef1);
            }
            else
            {
                EnterpriseBLL.Update(enterpriseRef1);
            }

            if (enterpriseRef2.EnterpriseGuid == Guid.Empty)
            {
                enterpriseRef2.EnterpriseGuid = Guid.NewGuid();
                EnterpriseBLL.Create(enterpriseRef2);
            }
            else
            {
                EnterpriseBLL.Update(enterpriseRef2);
            }

            SetCurrentLoanStep(30);

            return Json(logicStatusInfo);
        }

        #region 辅助方法
        private EnterpriseEntity CollecteEnterpriseRef(string postFix)
        {
            EnterpriseEntity entity = new EnterpriseEntity();
            string enterpriseGuidRef = RequestHelper.GetValue("EnterpriseGuid" + postFix);
            if (string.IsNullOrWhiteSpace(enterpriseGuidRef))
            {
                entity.EnterpriseGuid = Guid.Empty;
            }
            else
            {
                entity.EnterpriseGuid = new Guid(enterpriseGuidRef);
            }

            entity.ContactPerson = RequestHelper.GetValue("ContactName" + postFix);
            entity.CompanyName = RequestHelper.GetValue("CompanyName" + postFix);
            entity.Telephone = RequestHelper.GetValue("Telephone" + postFix);

            return entity;
        }
        #endregion
        #endregion

        #region step4
        public ActionResult LiabilityStatement()
        {
            SetCurrentLoanLayout();
            return View();
        }

        public ActionResult ULiabilityStatementWrapper()
        {
            BrokeLoanParam();
            return View();
        }

        public ActionResult ULiabilityStatementList()
        {
            BrokeLoanParam();

            List<LiabilityEntity> entityList = GetLiabilityList();
            return View(entityList);
        }

        [HttpPost]
        public ActionResult ULiabilityStatementList(Guid? entityGuidToDelete)
        {
            BrokeLoanParam();

            if (entityGuidToDelete.HasValue && entityGuidToDelete.Value != Guid.Empty)
            {
                LiabilityBLL.Delete(entityGuidToDelete.Value);
            }

            List<LiabilityEntity> entityList = GetLiabilityList();
            return View(entityList);
        }

        private List<LiabilityEntity> GetLiabilityList()
        {
            List<LiabilityEntity> entityList = new List<LiabilityEntity>();
            string whereCluase = string.Format("UserGuid='{0}'", Miscs.CurrentLoanSimpleInfo.EnterpriseGuid.ToString());
            entityList = LiabilityBLL.GetList(whereCluase);
            return entityList;
        }

        [HttpPost]
        public ActionResult ULiabilityStatementDeleteRow(string itemIDToDelete)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();
            if (string.IsNullOrWhiteSpace(itemIDToDelete) == false && itemIDToDelete != Guid.Empty.ToString())
            {
                logicStatusInfo.IsSuccessful = LiabilityBLL.Delete(new Guid(itemIDToDelete));
            }

            return Json(logicStatusInfo);
        }

        /// <summary>
        /// 给列表添加行
        /// </summary>
        /// <param name="rowNumber"></param>
        /// <param name="entity"></param>
        /// <param name="usingModeInput"></param>
        /// <returns></returns>
        public ActionResult ULiabilityStatementAddRow(int rowNumber, LiabilityEntity entity, MvcControlUsingModes? usingModeInput)
        {
            MvcControlUsingModes usingMode = MvcControlUsingModes.Editable;
            if (usingModeInput.HasValue)
            {
                usingMode = usingModeInput.Value;
            }
            if (entity == null)
            {
                entity = new LiabilityEntity();
            }

            string LiabilityGuidString = HtmlHelperEx.HiHidden().Name("LiabilityGuid_" + rowNumber).Value(entity.LiabilityGuid).UsingMode(usingMode).Render().ToString();
            string LiabilityLenderInfoString = HtmlHelperEx.HiTextBox().Name("LiabilityLenderInfo_" + rowNumber).Value(entity.LiabilityLenderInfo).UsingMode(usingMode).Render().ToString();
            string LiabilityAmountOwingString = HtmlHelperEx.HiTextBox().Name("LiabilityAmountOwing_" + rowNumber).Value(entity.LiabilityAmountOwing.ToString()).UsingMode(usingMode).Render().ToString();
            string LiabilityPaymentMonthlyString = HtmlHelperEx.HiTextBox().Name("LiabilityPaymentMonthly_" + rowNumber).Value(entity.LiabilityPaymentMonthly.ToString()).UsingMode(usingMode).Render().ToString();
            string OpereationString = string.Empty;
            if (entity.LiabilityGuid != Guid.Empty)
            {
                OpereationString = string.Format("<a itemGuid=\"{0}\" class=\"operateEntry deleteEntry\">DELETE</a>", entity.LiabilityGuid);
            }

            string result = string.Format("<tr><td>{0} {1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td>", rowNumber + 1, LiabilityGuidString, LiabilityLenderInfoString, LiabilityAmountOwingString, LiabilityPaymentMonthlyString, OpereationString);
            return Content(result);
        }

        public ActionResult ULiabilityStatementDetails()
        {
            string whereClause = string.Format(" UserGuid='{0}' ", Miscs.CurrentLoanSimpleInfo.EnterpriseGuid);
            List<LiabilityEntity> entityList = LiabilityBLL.GetList(whereClause);

            BrokeLoanParam();
            return View(entityList);
        }

        [HttpPost]
        public ActionResult ULiabilityStatementDetails(bool? onlyPlaceHolder)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();

            int rowCountToFeedback = 0;
            string rowCountToFeedbackString = RequestHelper.GetValue("rowCountToFeedback");
            if (string.IsNullOrWhiteSpace(rowCountToFeedbackString) == false)
            {
                rowCountToFeedback = Converter.TryToInt32(rowCountToFeedbackString);
            }

            if (rowCountToFeedback > 0)
            {
                for (int i = 0; i < rowCountToFeedback; i++)
                {
                    bool isNewEntity = false;
                    bool isNeedSave = false;
                    LiabilityEntity entity = new LiabilityEntity();
                    string LiabilityGuidString = RequestHelper.GetValue("LiabilityGuid_" + i);
                    if (string.IsNullOrWhiteSpace(LiabilityGuidString) || LiabilityGuidString == Guid.Empty.ToString())
                    {
                        isNewEntity = true;
                        entity.UserGuid = Miscs.CurrentLoanSimpleInfo.EnterpriseGuid;
                    }
                    else
                    {
                        isNewEntity = false;
                        isNeedSave = true;
                        Guid LiabilityGuid = new Guid(LiabilityGuidString);
                        entity = LiabilityBLL.Get(LiabilityGuid);
                    }

                    string LiabilityLenderInfoString = RequestHelper.GetValue("LiabilityLenderInfo_" + i);
                    if (string.IsNullOrWhiteSpace(LiabilityLenderInfoString) == false)
                    {
                        isNeedSave = true;
                        entity.LiabilityLenderInfo = LiabilityLenderInfoString;
                    }

                    string LiabilityAmountOwingString = RequestHelper.GetValue("LiabilityAmountOwing_" + i);
                    if (string.IsNullOrWhiteSpace(LiabilityAmountOwingString) == false)
                    {
                        decimal LiabilityAmountOwing = Converter.TryToDecimal(LiabilityAmountOwingString);
                        if (LiabilityAmountOwing != 0)
                        {
                            isNeedSave = true;
                            entity.LiabilityAmountOwing = LiabilityAmountOwing;
                        }
                    }

                    string LiabilityPaymentMonthlyString = RequestHelper.GetValue("LiabilityPaymentMonthly_" + i);
                    if (string.IsNullOrWhiteSpace(LiabilityPaymentMonthlyString) == false)
                    {
                        decimal LiabilityPaymentMonthly = Converter.TryToDecimal(LiabilityPaymentMonthlyString);
                        if (LiabilityPaymentMonthly != 0)
                        {
                            isNeedSave = true;
                            entity.LiabilityPaymentMonthly = LiabilityPaymentMonthly;
                        }
                    }

                    if (isNeedSave == true)
                    {
                        if (isNewEntity == true)
                        {
                            LiabilityBLL.Create(entity);
                        }
                        else
                        {
                            LiabilityBLL.Update(entity);
                        }
                    }
                }
            }

            logicStatusInfo.IsSuccessful = true;
            SetCurrentLoanStep(40);

            return Json(logicStatusInfo);
        }
        #endregion

        #region step5
        public ActionResult AssetStatement()
        {
            SetCurrentLoanLayout();
            return View();
        }

        public ActionResult UAssetStatementWrapper()
        {
            BrokeLoanParam();
            return View();
        }

        public ActionResult UAssetStatementList()
        {
            BrokeLoanParam();

            List<IncomeAssetEntity> entityList = GetAssetStatementList();
            return View(entityList);
        }

        [HttpPost]
        public ActionResult UAssetStatementList(Guid? entityGuidToDelete)
        {
            BrokeLoanParam();

            if (entityGuidToDelete.HasValue && entityGuidToDelete.Value != Guid.Empty)
            {
                IncomeAssetBLL.Delete(entityGuidToDelete.Value);
            }

            List<IncomeAssetEntity> entityList = GetAssetStatementList();
            return View(entityList);
        }

        private List<IncomeAssetEntity> GetAssetStatementList()
        {
            List<IncomeAssetEntity> entityList = new List<IncomeAssetEntity>();

            string whereCluase = string.Format("UserGuid='{0}'", Miscs.CurrentLoanSimpleInfo.EnterpriseGuid.ToString());
            entityList = IncomeAssetBLL.GetList(whereCluase);
            return entityList;
        }

        [HttpPost]
        public ActionResult UAssetStatementDeleteRow(string itemIDToDelete)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();
            if (string.IsNullOrWhiteSpace(itemIDToDelete) == false && itemIDToDelete != Guid.Empty.ToString())
            {
                logicStatusInfo.IsSuccessful = IncomeAssetBLL.Delete(new Guid(itemIDToDelete));
            }

            return Json(logicStatusInfo);
        }

        /// <summary>
        /// 给列表添加行
        /// </summary>
        /// <param name="rowNumber"></param>
        /// <param name="entity"></param>
        /// <param name="usingModeInput"></param>
        /// <returns></returns>
        public ActionResult UAssetStatementAddRow(int rowNumber, IncomeAssetEntity entity, MvcControlUsingModes? usingModeInput)
        {
            MvcControlUsingModes usingMode = MvcControlUsingModes.Editable;
            if (usingModeInput.HasValue)
            {
                usingMode = usingModeInput.Value;
            }
            if (entity == null)
            {
                entity = new IncomeAssetEntity();
            }

            string itemGuidString = HtmlHelperEx.HiHidden().Name("ItemGuid_" + rowNumber).Value(entity.ItemGuid.ToString()).UsingMode(usingMode).Render().ToString();
            string ItemNameString = HtmlHelperEx.HiTextBox().Name("ItemName_" + rowNumber).Value(entity.ItemName).UsingMode(usingMode).Render().ToString();
            string ItemValueString = HtmlHelperEx.HiTextBox().Name("ItemValue_" + rowNumber).Value(entity.ItemValue.ToString()).UsingMode(usingMode).Render().ToString();
            string OpereationString = string.Empty;
            if (entity.ItemGuid != Guid.Empty)
            {
                OpereationString = string.Format("<a itemGuid=\"{0}\" class=\"operateEntry deleteEntry\">DELETE</a>", entity.ItemGuid);
            }

            string result = string.Format("<tr><td>{0} {1}</td><td>{2}</td><td>{3}</td><td>{4}</td>", rowNumber + 1, itemGuidString, ItemNameString, ItemValueString, OpereationString);
            return Content(result);
        }

        public ActionResult UAssetStatementDetails()
        {
            string whereClause = string.Format(" UserGuid='{0}' ", Miscs.CurrentLoanSimpleInfo.EnterpriseGuid);
            List<IncomeAssetEntity> entityList = IncomeAssetBLL.GetList(whereClause);

            BrokeLoanParam();

            return View(entityList);
        }

        [HttpPost]
        public ActionResult UAssetStatementDetails(bool? onlyPlaceHolder)
        {
            BrokeLoanParam();

            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();

            int rowCountToFeedback = 0;
            string rowCountToFeedbackString = RequestHelper.GetValue("rowCountToFeedback");
            if (string.IsNullOrWhiteSpace(rowCountToFeedbackString) == false)
            {
                rowCountToFeedback = Converter.TryToInt32(rowCountToFeedbackString);
            }

            if (rowCountToFeedback > 0)
            {
                for (int i = 0; i < rowCountToFeedback; i++)
                {
                    bool isNewEntity = false;
                    bool isNeedSave = false;
                    IncomeAssetEntity entity = new IncomeAssetEntity();
                    string ItemGuidString = RequestHelper.GetValue("ItemGuid_" + i);
                    if (string.IsNullOrWhiteSpace(ItemGuidString) || ItemGuidString == Guid.Empty.ToString())
                    {
                        isNewEntity = true;
                        entity.UserGuid = Miscs.CurrentLoanSimpleInfo.EnterpriseGuid;
                    }
                    else
                    {
                        isNewEntity = false;
                        isNeedSave = true;
                        Guid ItemGuid = new Guid(ItemGuidString);
                        entity = IncomeAssetBLL.Get(ItemGuid);
                    }

                    string ItemNameString = RequestHelper.GetValue("ItemName_" + i);
                    if (string.IsNullOrWhiteSpace(ItemNameString) == false)
                    {
                        isNeedSave = true;
                        entity.ItemName = ItemNameString;
                    }

                    string ItemValueString = RequestHelper.GetValue("ItemValue_" + i);
                    if (string.IsNullOrWhiteSpace(ItemValueString) == false)
                    {
                        decimal ItemValue = Converter.TryToDecimal(ItemValueString);
                        if (ItemValue != 0)
                        {
                            isNeedSave = true;
                            entity.ItemValue = ItemValue;
                        }
                    }

                    if (isNeedSave == true)
                    {
                        if (isNewEntity == true)
                        {
                            IncomeAssetBLL.Create(entity);
                        }
                        else
                        {
                            IncomeAssetBLL.Update(entity);
                        }
                    }
                }
            }

            logicStatusInfo.IsSuccessful = true;
            SetCurrentLoanStep(50);
            return Json(logicStatusInfo);
        }
        #endregion

        #region step6
        public ActionResult AboutTheSecurities()
        {
            SetCurrentLoanLayout();
            return View();
        }

        [HttpPost]
        public ActionResult UAboutTheSecuritiesDeleteRow(string itemIDToDelete)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();
            if (string.IsNullOrWhiteSpace(itemIDToDelete) == false && itemIDToDelete != Guid.Empty.ToString())
            {
                logicStatusInfo.IsSuccessful = SecuredPropertyBLL.Delete(new Guid(itemIDToDelete));
            }

            return Json(logicStatusInfo);
        }

        /// <summary>
        /// 给列表添加行
        /// </summary>
        /// <param name="rowNumber"></param>
        /// <param name="entity"></param>
        /// <param name="usingModeInput"></param>
        /// <returns></returns>
        public ActionResult UAboutTheSecuritiesAddRow(int rowNumber, SecuredPropertyEntity entity, MvcControlUsingModes? usingModeInput)
        {
            MvcControlUsingModes usingMode = MvcControlUsingModes.Editable;
            if (usingModeInput.HasValue)
            {
                usingMode = usingModeInput.Value;
            }
            if (entity == null)
            {
                entity = new SecuredPropertyEntity();
            }

            string ItemGuidString = HtmlHelperEx.HiHidden().Name("ItemGuid_" + rowNumber).Value(entity.ItemGuid).UsingMode(usingMode).Render().ToString();
            string ItemDetailString = HtmlHelperEx.HiTextBox().Name("ItemDetail_" + rowNumber).Value(entity.ItemDetail).UsingMode(usingMode).Render().ToString();
            string ItemOwerNameString = HtmlHelperEx.HiTextBox().Name("ItemOwerName_" + rowNumber).Value(entity.ItemOwerName).UsingMode(usingMode).Render().ToString();
            string ItemValueString = HtmlHelperEx.HiTextBox().Name("ItemValue_" + rowNumber).Value(entity.ItemValue.ToString()).UsingMode(usingMode).Render().ToString();
            string OpereationString = string.Empty;
            if (entity.ItemGuid != Guid.Empty)
            {
                OpereationString = string.Format("<a itemGuid=\"{0}\" class=\"operateEntry deleteEntry\">DELETE</a>", entity.ItemGuid);
            }

            string result = string.Format("<tr><td>{0} {1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td>", rowNumber + 1, ItemGuidString, ItemDetailString, ItemOwerNameString, ItemValueString, OpereationString);
            return Content(result);
        }

        public ActionResult UAboutTheSecuritiesDetails()
        {
            string whereClause = string.Format(" UserGuid='{0}' ", Miscs.CurrentLoanSimpleInfo.EnterpriseGuid);
            List<SecuredPropertyEntity> entityList = SecuredPropertyBLL.GetList(whereClause);

            BrokeLoanParam();
            return View(entityList);
        }

        [HttpPost]
        public ActionResult UAboutTheSecuritiesDetails(bool? onlyPlaceHolder)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();
            int rowCountToFeedback = 0;
            string rowCountToFeedbackString = RequestHelper.GetValue("rowCountToFeedback");
            if (string.IsNullOrWhiteSpace(rowCountToFeedbackString) == false)
            {
                rowCountToFeedback = Converter.TryToInt32(rowCountToFeedbackString);
            }

            if (rowCountToFeedback > 0)
            {
                for (int i = 0; i < rowCountToFeedback; i++)
                {
                    bool isNewEntity = false;
                    bool isNeedSave = false;
                    SecuredPropertyEntity entity = new SecuredPropertyEntity();
                    string ItemGuidString = RequestHelper.GetValue("ItemGuid_" + i);
                    if (string.IsNullOrWhiteSpace(ItemGuidString) || ItemGuidString == Guid.Empty.ToString())
                    {
                        isNewEntity = true;
                        entity.UserGuid = Miscs.CurrentLoanSimpleInfo.EnterpriseGuid;
                    }
                    else
                    {
                        isNewEntity = false;
                        isNeedSave = true;
                        Guid LiabilityGuid = new Guid(ItemGuidString);
                        entity = SecuredPropertyBLL.Get(LiabilityGuid);
                    }

                    string ItemDetailString = RequestHelper.GetValue("ItemDetail_" + i);
                    if (string.IsNullOrWhiteSpace(ItemDetailString) == false)
                    {
                        isNeedSave = true;
                        entity.ItemDetail = ItemDetailString;
                    }

                    string ItemOwerNameString = RequestHelper.GetValue("ItemOwerName_" + i);
                    if (string.IsNullOrWhiteSpace(ItemOwerNameString) == false)
                    {
                            isNeedSave = true;
                            entity.ItemOwerName = ItemOwerNameString;
                    }

                    string ItemValueString = RequestHelper.GetValue("ItemValue_" + i);
                    if (string.IsNullOrWhiteSpace(ItemValueString) == false)
                    {
                        decimal ItemValue = Converter.TryToDecimal(ItemValueString);
                        if (ItemValue != 0)
                        {
                            isNeedSave = true;
                            entity.ItemValue = ItemValue;
                        }
                    }

                    if (isNeedSave == true)
                    {
                        if (isNewEntity == true)
                        {
                            SecuredPropertyBLL.Create(entity);
                        }
                        else
                        {
                            SecuredPropertyBLL.Update(entity);
                        }
                    }
                }
            }

            logicStatusInfo.IsSuccessful = true;

            SetCurrentLoanStep(60);
            return Json(logicStatusInfo);
        }

        public ActionResult UAboutTheSecuritiesList()
        {
            BrokeLoanParam();

            List<SecuredPropertyEntity> securedPropertyList = GetSecuredPropertyList();
            return View(securedPropertyList);
        }

        [HttpPost]
        public ActionResult UAboutTheSecuritiesList(Guid? entityGuidToDelete)
        {
            BrokeLoanParam();

            if (entityGuidToDelete.HasValue && entityGuidToDelete.Value != Guid.Empty)
            {
                SecuredPropertyBLL.Delete(entityGuidToDelete.Value);
            }

            List<SecuredPropertyEntity> securedPropertyList = GetSecuredPropertyList();
            return View(securedPropertyList);
        }

        private List<SecuredPropertyEntity> GetSecuredPropertyList()
        {
            List<SecuredPropertyEntity> securedPropertyList = new List<SecuredPropertyEntity>();
            string whereCluase = string.Format("UserGuid='{0}'", Miscs.CurrentLoanSimpleInfo.EnterpriseGuid.ToString());
            securedPropertyList = SecuredPropertyBLL.GetList(whereCluase);
            return securedPropertyList;
        }
        #endregion

        #region step7
        public ActionResult BusinessBankDetails()
        {
            SetCurrentLoanLayout();
            return View();
        }

        public ActionResult UBusinessBankDetails()
        {
            BrokeLoanParam();

            BankEntity bankEntity = new BankEntity();

            LoanCookie loanCookie = LoadCurrentLoanCookie(); //CookieInfo.Load<SecuredLoanCookie>();
            string enterpriseGuidString = loanCookie.EnterpriseGuid;
            Guid enterpriseGuid = Guid.Empty;
            if (string.IsNullOrWhiteSpace(enterpriseGuidString) || enterpriseGuidString == Guid.Empty.ToString())
            {
                //enterpriseGuid = Guid.NewGuid();
            }
            else
            {
                //enterpriseGuid = new Guid(enterpriseGuidString);
                string whereClause = string.Format("UserGuid='{0}'", enterpriseGuidString);
                List<BankEntity> bankList = BankBLL.GetList(whereClause);
                if (bankList != null && bankList.Count > 0)
                {
                    bankEntity = bankList[0];
                }
            }


            return View(bankEntity);
        }

        [HttpPost]
        public ActionResult UBusinessBankDetails(BankEntity bankEntity)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();
            LoanCookie loanCookie = LoadCurrentLoanCookie(); //CookieInfo.Load<SecuredLoanCookie>();
            string enterpriseGuidString = loanCookie.EnterpriseGuid;
            Guid enterpriseGuid = Guid.Empty;
            if (string.IsNullOrWhiteSpace(enterpriseGuidString) || enterpriseGuidString == Guid.Empty.ToString())
            {
                enterpriseGuid = Guid.NewGuid();
            }
            else
            {
                enterpriseGuid = new Guid(enterpriseGuidString);
            }
            bankEntity.UserGuid = enterpriseGuid;

            if (bankEntity.BankGuid == Guid.Empty)
            {
                bankEntity.BankGuid = Guid.NewGuid();

                logicStatusInfo.IsSuccessful = BankBLL.Create(bankEntity);
            }
            else
            {
                logicStatusInfo.IsSuccessful = BankBLL.Update(bankEntity);
            }

            SetCurrentLoanStep(70);

            return Json(logicStatusInfo);
        }
        #endregion

        #region step8
        public ActionResult ApplicationSummary()
        {
            SetCurrentLoanStep(80);
            SetCurrentLoanLayout();
            return View();
        }

        [HttpPost]
        public ActionResult ApplicationSummary(string onlyPlaceHolder)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo(true);
            return View(logicStatusInfo);
        }

        public ActionResult UApplicationSummary()
        {
            return View();
        }
        #endregion

        #region step9
        public ActionResult SubmitApplication()
        {
            SetCurrentLoanLayout();
            return View();
        }

        [HttpPost]
        public ActionResult SubmitApplication(string signedFullName)
        {
            SetCurrentLoanLayout();
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();
            if (string.IsNullOrWhiteSpace(signedFullName) == false)
            {
                EnterpriseEntity enterpriseEntity = EnterpriseBLL.Get(Miscs.CurrentLoanSimpleInfo.EnterpriseGuid);
                if (enterpriseEntity != null)
                {
                    enterpriseEntity.CompanyNameShort = signedFullName;
                    logicStatusInfo.IsSuccessful = EnterpriseBLL.Update(enterpriseEntity);
                }

                LoanBasicEntity loanEntity = LoanBasicBLL.Get(Miscs.CurrentLoanSimpleInfo.LoanGuid);
                if (loanEntity != null)
                {
                    loanEntity.LoanStatus = LoanStatuses.UserCompleted;
                    logicStatusInfo.IsSuccessful = LoanBasicBLL.Update(loanEntity);
                }
                //SetCurrentLoanStep(90);
                //清空Loan的cookie
                LoanCookie loanCookie = LoadCurrentLoanCookie();
                loanCookie.Reset();
            }

            return Json(logicStatusInfo);
        }
        #endregion

        #region step10
        public ActionResult FinalStep()
        {
            SetCurrentLoanLayout();
            return View();
        }
        #endregion

        #region 辅助方法
        /// <summary>
        /// 设置当前执行贷款的步骤数
        /// </summary>
        /// <param name="step"></param>
        private void SetCurrentLoanStep(int step)
        {
            LoanTypes loanType = Miscs.GetCurrentLoanType();

            if (loanType == LoanTypes.Secured)
            {
                Miscs.SetLoanStep<SecuredLoanCookie>(step);
            }
            else
            {
                Miscs.SetLoanStep<UnSecuredLoanCookie>(step);
            }
        }

        /// <summary>
        /// 载入当前执行贷款的Cookie
        /// </summary>
        /// <returns></returns>
        private LoanCookie LoadCurrentLoanCookie()
        {
            LoanTypes loanType = Miscs.GetCurrentLoanType();
            LoanCookie loanCookie;

            if (loanType == LoanTypes.Secured)
            {
                loanCookie = CookieInfo.Load<SecuredLoanCookie>();
            }
            else
            {
                loanCookie = CookieInfo.Load<UnSecuredLoanCookie>();
            }

            return loanCookie;
        }

        /// <summary>
        /// 重置当前执行贷款的Cookie
        /// </summary>
        private void ResetCurrentLoanCookie()
        {
            LoanTypes loanType = Miscs.GetCurrentLoanType();

            if (loanType == LoanTypes.Secured)
            {
                Miscs.ResetLoanCookie<SecuredLoanCookie>();
            }
            else
            {
                Miscs.ResetLoanCookie<UnSecuredLoanCookie>();
            }
        }

        /// <summary>
        /// 设置当前执行贷款的模板页
        /// </summary>
        private void SetCurrentLoanLayout()
        {
            LoanTypes loanType = Miscs.GetCurrentLoanType();

            if (loanType == LoanTypes.Secured)
            {
                this.ViewData["_Layout"] = CodeUtils.LayoutPathForSecured;
            }
            else
            {
                this.ViewData["_Layout"] = CodeUtils.LayoutPathForUnSecured;
            }
        }

        private decimal GetCurrentLoanRate()
        {
            decimal rate = 0.48M;
            LoanBasicSetting basicSetting = new LoanBasicSetting();
            LoanTypes loanType = Miscs.GetCurrentLoanType();
            if (loanType == LoanTypes.Secured)
            {
                rate = basicSetting.SecuredLoansAnnualInterest;
            }
            else
            {
                rate = basicSetting.UnSecuredLoansAnnualInterest;
            }

            return rate;
        }


        /// <summary>
        /// 判断当前页面是现实状态还是编辑状态（供View使用）
        /// </summary>
        /// <returns></returns>
        public MvcControlUsingModes GetUsingMode()
        {
            MvcControlUsingModes usingMode = MvcControlUsingModes.Editable;
            if (this.ViewData["usingMode"] != null)
            {
                string usingModeString = this.ViewData["usingMode"].ToString();
                int usingModeInt = (int)usingMode;
                int.TryParse(usingModeString, out usingModeInt);
                usingMode = (MvcControlUsingModes)usingModeInt;
            }

            return usingMode;
        }

        /// <summary>
        /// 判断当前页面是内嵌状态还是弹出状态（供View使用）
        /// </summary>
        /// <returns></returns>
        public bool CheckIsPopLayer()
        {
            bool isPopLayer = false;
            if (this.ViewData["IsPopLayer"] != null)
            {
                string isPopLayerString = this.ViewData["IsPopLayer"].ToString();
                bool.TryParse(isPopLayerString, out isPopLayer);
            }
            return isPopLayer;
        }

        /// <summary>
        /// 在Controller中接受参数并传递到View中
        /// </summary>
        public void BrokeLoanParam()
        {
            this.BrokeParam("isPopLayer");
            this.BrokeParam("usingMode");
        }
        #endregion

        #region 测试方法
        public ActionResult Test()
        {
            return View();
        }

        #endregion
    }
}
